package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.PhotoCategoryItem;
import org.abettor.nookinfo.persist.PhotoHelper;
import org.abettor.nookinfo.service.PhotoUpdateReceiver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 图片分类菜单页
 * @author shawn
 *
 */
public class PhotoCategory extends Activity
{
	private static final int ICON_WIDTH = 64;
	private static final int ICON_HEIGHT = 64;
	private float scaleRatio;
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final int REFRESHED = 1;//菜单更新已完成事件
	private static final int FAILED = 2;//菜单更新失败时间
	private YoumiManager youmi = new YoumiManager(this);
	private List<PhotoCategoryItem> categoryList = new ArrayList<PhotoCategoryItem>();
	private PhotoHelper photoHelper = new PhotoHelper(this);
	private ProgressDialog progressDialog = null;//进度条对话框
	private Worker worker = null;//网络访问线程
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				//	将从网上更新来的菜单信息绘制到界面上
				LinearLayout layout = (LinearLayout) findViewById(R.id.photoCategoryLayout);
				layout.removeAllViews();
				for(PhotoCategoryItem category : categoryList)
				{
					final PhotoCategoryItem theCategory = category;
					showView(layout, theCategory);
				}
				ScrollView scroll = (ScrollView) findViewById(R.id.photoCategoryScroll);
				scroll.scrollTo(0, 0);

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 25)
				{
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE, Color.BLACK, 0xAA);
				}
			}
			else if(msg.what == FAILED)
			{
				Builder builder = new Builder(PhotoCategory.this);
				builder.setTitle(R.string.photo_category_fail_title);
				builder.setMessage(R.string.photo_category_fail_content);
				builder.setPositiveButton(R.string.photo_category_fail_btn_ok, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialoginterface, int i)
					{
						dialoginterface.dismiss();
					}
				});
				builder.show();
			}
			super.handleMessage(msg);
		}

		//	显示列表视图中的一个元素
		private void showView(LinearLayout layout, final PhotoCategoryItem theCategory)
		{
			//	首先是一个横向的布局
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0f);
			params.gravity = 0x30;
			LinearLayout item = new LinearLayout(PhotoCategory.this);
			item.setOrientation(LinearLayout.HORIZONTAL);
			item.setLayoutParams(params);
			layout.addView(item);
			item.setClickable(true);
			item.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Bundle extras = new Bundle();
					extras.putInt(PhotoDailyList.PHOTO_CATEGORY_ID, theCategory.id);
					extras.putString(PhotoDailyList.PHOTO_CATEGORY_NAME, theCategory.name);
					Intent photoListIntent = new Intent();
					photoListIntent.setClass(PhotoCategory.this, PhotoDailyList.class);
					photoListIntent.putExtras(extras);
					startActivity(photoListIntent);
				}
			});
			item.setOnTouchListener(new OnTouchListener()
			{
				@Override
				public boolean onTouch(View view, MotionEvent motionevent)
				{
					LinearLayout layout = (LinearLayout) view;
					int action = motionevent.getAction();
					if(action == MotionEvent.ACTION_DOWN)
					{
						layout.setBackgroundColor(Color.GREEN);
					}
					else if(action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_OUTSIDE)
					{
						layout.setBackgroundColor(Color.TRANSPARENT);
					}

					return false;
				}
			});

			//	图片
			InputStream is = null;
			try
			{
				String path = AddressConstant.PHOTO_CATEGORY_IMAGE_LOCAL.replace("ID", theCategory.id + "");
				File file = new File(path);
				is = new FileInputStream(file);
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				ImageView imageView = new ImageView(PhotoCategory.this);
				imageView.setImageBitmap(bitmap);
				imageView.setMaxWidth((int) (ICON_WIDTH * scaleRatio));
				imageView.setMaxHeight((int) (ICON_HEIGHT * scaleRatio));
				imageView.setMinimumWidth((int) (ICON_WIDTH * scaleRatio));
				imageView.setMinimumHeight((int) (ICON_HEIGHT * scaleRatio));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				item.addView(imageView);
			}
			catch(Exception e)
			{
				Log.d(this.getClass().getName(), "", e);
			}
			finally
			{
				if(is != null)
				{
					try { is.close(); } catch (Exception e) { };
				}
			}

			//	右边一个上下结构的布局
			params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0f);
			params.gravity = 0x03 | 0x30;
			LinearLayout itemRight = new LinearLayout(PhotoCategory.this);
			itemRight.setPadding(5, 0, 0, 0);
			itemRight.setOrientation(LinearLayout.VERTICAL);
			itemRight.setLayoutParams(params);
			item.addView(itemRight);

			//	右上方名称
			TextView nameView = new TextView(PhotoCategory.this);
			nameView.setText(theCategory.name);
			nameView.setGravity(0x03 | 0x30);
			nameView.setTextColor(Color.BLACK);
			nameView.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
			itemRight.addView(nameView);

			//	右侧更新时间
			TextView updateView = new TextView(PhotoCategory.this);
			updateView.setText(sdf.format(theCategory.update));
			updateView.setGravity(0x03 | 0x30);
			updateView.setTextColor(Color.BLACK);
			updateView.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
			itemRight.addView(updateView);

			//	右下方简介
			TextView summary = new TextView(PhotoCategory.this);
			summary.setText(theCategory.summary);
			summary.setGravity(0x03 | 0x30);
			summary.setTextColor(0xAA000000);
			itemRight.addView(summary);

			//	最后再显示一个条分割线比较好
			ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 3);
			TextView seperator = new TextView(PhotoCategory.this);
			seperator.setBackgroundColor(0x88888888);
			seperator.setLayoutParams(layoutParams);
			layout.addView(seperator);

			//	保存到本地数据库
			PhotoHelper.PhotoCategory cate = new PhotoHelper.PhotoCategory();
			cate.id = theCategory.id;
			cate.name = theCategory.name;
			cate.description = theCategory.summary;
			cate.update = theCategory.update;
			photoHelper.saveOrUpdateCategory(cate);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_category);
		onUpdateClicked(null);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		scaleRatio = dm.density;

		//	取消更新通知
		NotificationManager notiMgm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notiMgm.cancel(PhotoUpdateReceiver.NOTIFICATION_TAG, 0);
	}

	/**
	 * “更新”按钮事件方法
	 * @param v
	 */
	public void onUpdateClicked(View v)
	{
		//如果确定点击的是更新按钮，就删除已保存的图片文件
		if(v != null && v.getId() == R.id.photoCategoryUpdate)
		{
			for(PhotoCategoryItem item : categoryList)
			{
				String path = AddressConstant.PHOTO_CATEGORY_IMAGE_LOCAL.replace("ID", item.id + "");
				File file = new File(path);
				if(file.exists())
				{
					file.delete();
				}
			}
		}

		//	开始更新
		categoryList.clear();
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.photo_category_progress_title);
		progressDialog.setMessage(getText(R.string.photo_category_progress_content));
		progressDialog.setButton(getText(R.string.photo_category_progress_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialoginterface, int i)
			{
				worker.kill();
			}
		});
		progressDialog.show();
		synchronized (worker)
		{
			worker.notify();
		}
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onExitClicked(View v)
	{
		finish();
	}

	/**
	 * 网络连接并更新菜单信息的工作者线程
	 * @author shawn
	 *
	 */
	private class Worker extends Thread
	{
		//	线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill()
		{
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run()
		{
			try
			{
				//	等待对话框创建完成
				synchronized (this)
				{
					wait();
				}

				//	此处访问网络并获取图片分类菜单
				fetchCategories(categoryList);

				//	关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if(! cancel)
				{
					//	在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				}
				else
				{
					//	意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			}
			catch (Exception e)
			{
				//	清除按钮列表
				try { progressDialog.dismiss(); } catch (Exception ex) { };
				categoryList.clear();
				//	意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		//	读取图片分类信息
		private void fetchCategories(List<PhotoCategoryItem> categoryList) throws Exception
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(AddressConstant.PHOTO_CATEGORY);
			NodeList list = doc.getElementsByTagName("category");
			int len = list.getLength();
			for(int i = 0; i < len; i ++)
			{
				PhotoCategoryItem item = new PhotoCategoryItem();
				Node node = list.item(i);
				NodeList nodes = node.getChildNodes();
				int count = nodes.getLength();
				for(int j = 0; j < count; j ++)
				{
					Node itemNode = nodes.item(j);
					String nodeName = itemNode.getNodeName();
					if("id".equals(nodeName))
					{
						String id = itemNode.getTextContent();
						item.id = Integer.valueOf(id);
					}
					else if("name".equals(nodeName))
					{
						item.name = itemNode.getTextContent();
					}
					else if("update".equals(nodeName))
					{
						String update = itemNode.getTextContent();
						item.update = sdf.parse(update);
					}
					else if("summary".equals(nodeName))
					{
						item.summary = itemNode.getTextContent();
					}
				}

				//	获取类别图标并保存
				saveIcon(item.id);
				categoryList.add(item);
			}
		}

		//	根据图片分类的ID获取并保存其图标
		private void saveIcon(int id) throws Exception
		{
			String path = AddressConstant.PHOTO_CATEGORY_IMAGE_LOCAL.replace("ID", id + "");
			File file = new File(path);
			if(! file.exists())
			{
				String url = AddressConstant.PHOTO_CATEGORY_IMAGE.replace("ID", id + "");
				URL imgUrl = new URL(url);
				InputStream is = imgUrl.openStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				is.close();

				File dir = file.getParentFile();
				if(! dir.exists())
				{
					dir.mkdirs();
				}

				if(file.exists())
				{
					file.delete();
				}

				file.createNewFile();
				FileOutputStream os = new FileOutputStream(file);
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
				os.close();
			}
		}
	}
}
